<template>
  <div class="head-nav-search" :class="{active}">
    <span class="iconfont icon-search"></span>
    <input @focus="active=true" @blur="active=false" v-model="keyword" type="text" @keyup.enter="toSearch()" placeholder="搜一搜" />
  </div>
  <div class="tips-layer" :class="{active: isShow}" ref="target">
    <span>热门搜索：</span>
    <p>运动鞋、茶具、美食</p>
  </div>
</template>

<script>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { onClickOutside } from '@vueuse/core'
import { findTipsBysearch } from '@/api/product'
export default {
  name: 'app-header-search',
  setup () {
    const active = ref(false)
    const isShow = ref(false)
    const keyword = ref('')
    const router = useRouter()
    const toSearch = () => {
      router.push({ path: '/search', query: { keyword: keyword.value } })
      // 页面跳转之后将输入框内容置空
      keyword.value = ''
    }
    // 监听keyword值变化，根据不同keyword值获取与之关联的搜索提示语
    watch(() => keyword.value, (newVal) => {
      if (keyword.value !== '') {
        isShow.value = true
        // 调用搜索提示语接口
        findTipsBysearch(keyword.value).then(data => {
          console.log(data)
        })
      }
    }, { immediate: true })
    // 点击tips-layerdom对象的其他区域来关闭对象本身
    const target = ref(null)
    onClickOutside(target, () => {
      isShow.value = false
    })
    return { active, keyword, toSearch, isShow, target }
  }
}
</script>

<style scoped lang='less'>
  // 导航栏右侧搜索
  .head-nav-search {
    width: 170px;
    height: 32px;
    border-bottom: 2px solid #f4f4f4;
    position: relative;
    margin-top: 2px;
    &.active {
      border-color: @xtxColor;
    }
    .icon-search {
      position: absolute;
      left: 0;
      top: 0;
      font-size: 18px;
      color: #333;
      height: 37px;
      width: 37px;
      text-align: center;
    }
    input {
      width: 100%;
      height: 100%;
      color: #999;
      padding-left: 37px;
    }
  }
  .tips-layer {
    opacity: 0;
    position: absolute;
    background-color: #ffffff;
    width: 170px;
    height: auto;
    top: 85px;
    padding: 10px 10px;
    border: 1px solid #f1f1f1;
    box-shadow: 0 0 10px rgba(0,0,0,0.2);
    transition: all .4s .2s;
    transform: translateY(0px) scale(1, 0);
    right: 60px;
    z-index: 999;
    &.active {
      opacity: 1;
      transform: none
    }
    span {
      color: #ccc;
    }
    p {
      color: #afafaf;
      margin-top: 5px;
    }
  }
</style>
